google.load("jquery", "1.3.2");

google.setOnLoadCallback(function() {
  // generate html code for cards
  var card_values = [0, 1, 3, 5, 8, 13, 20, 40, 'N'];

  if (wave && wave.getState()) {
    var chosen = wave.getState().get(wave.getViewer().getId());
  }

  $.each(card_values, function() {
    var $ele = $('<input type="button" class="card" />');
    $ele.attr('id', 'card-' + this);
    $ele.val(this);

    chosen && chosen == this && $ele.addClass('chosen');

    $ele.click(function() {
      // if card is chosen, do nothing
      if ($(this).hasClass('chosen')) {
        return false;
      }

      // store participator's estimation
      wave.getState().submitValue(wave.getViewer().getId(), $(this).val());

      // give card class "chosen" after wave state is updated
      $('.card').removeClass('chosen');
      $('#card-' + $(this).val()).addClass('chosen');

      return false;
    });

    $('#card-wrapper').append($ele);
  });

});

/* callbacks */
function renderStatus() {
  if (!wave.getState()) {
    return;
  }

  // cards still face down, show how many cards have been chosen
  var finished = wave.getState().getKeys().length;
  var total = wave.getParticipants().length;

  if (finished < total) {
    if (0 == finished) {
      var output = "Nobody made choice yet."
    }
    else if (1 == finished) {
      var output = finished + " of " + total + " has made choice.";
    }
    else {
      var output = finished + " of " + total + " have made choices.";
    }
    $('#messages').html(output);
  }
  else if (finished == total) {
    // one round finished, print out estimations
    var $estimation_list = $('<ul id="estimation-list"><ul>');
    var state = wave.getState();
    $.each(state.getKeys(), function(key, value) {
      var participant = wave.getParticipantById(this);
      var $estimation = $('<li class="estimation"></li>');
      $estimation.html('<img class="participant-thumb" src="' + participant.getThumbnailUrl() + '" />: ' + state.get(this));

      $estimation_list.append($estimation);
    });

    $('#estimation-wrapper').empty().append($estimation_list);
  }
  else {
    // should NEVER go here
    wave.getState().reset();
  }
}

/* register wave handler */
gadgets.util.registerOnLoadHandler(function() {
  if (wave && wave.isInWaveContainer()) {
    wave.setStateCallback(renderStatus);
    wave.setParticipantCallback(renderStatus);
  }
});
